import axios from 'axios';

const api = axios.create({
  baseURL: 'http://localhost:8080/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// 用户接口类型定义
export interface User {
  userId?: number;
  username: string;
  password?: string;
  realName?: string;
  email?: string;
  phone?: string;
  createdAt?: string;
  updatedAt?: string;
  roles?: string[];
}

export interface LoginRequest {
  username: string;
  password: string;
}

export interface RegisterRequest {
  username: string;
  password: string;
  email: string;
  realName?: string;
  phone?: string;
}

export interface ApiResponse<T = any> {
  operateResult: string;
  errorMsg?: string;
  data?: T;
  message?: string;
}

// 用户API
export const userApi = {
  // 登录
  login: (credentials: LoginRequest) => 
    api.post<ApiResponse<User>>('/users/login', credentials),
  
  // 注册
  register: (userData: RegisterRequest) => 
    api.post<ApiResponse>('/users/register', userData),
  
  // 获取所有用户
  getAllUsers: () => 
    api.get<ApiResponse<User[]>>('/users'),
  
  // 根据用户名获取用户
  getUserByUsername: (username: string) => 
    api.get<ApiResponse<User>>(`/users/${username}`),
  
  // 更新用户
  updateUser: (userData: User) => 
    api.put<ApiResponse>('/users', userData),
  
  // 删除用户
  deleteUser: (username: string) => 
    api.delete<ApiResponse>(`/users/${username}`),
  
  // 获取用户角色
  getUserRoles: (username: string) => 
    api.get<ApiResponse<string[]>>(`/users/${username}/roles`),
  
  // 更新用户角色
  updateUserRoles: (username: string, roleIds: number[]) => 
    api.put<ApiResponse>(`/users/${username}/roles`, roleIds)
};

export default api;